﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BasePlatformNet;
using BasePlatformCommon.devChain;
using BasePlatformCommon;

namespace L9SubSet
{
    public partial class Form_SelectSub : Form
    {
        private const int PortGroupHeight = 33;
		private SelectedSubInfo selectedSubInfo = null;

		private string mode = "";

		private BaseCoreNet baseCoreNet = null;

		private int totalSubCtrlNum = 0;
		private int totalSubCtrlNumInLwf = 0;

        public int selectMode = 0;
        public int startSub = -1;
        public int endSub = -1;
        public int startPort = -1;
        public int endPort = -1;

		private string section = "SelectSub";			// 多语言文件配置节名称

		private string tip = "提示";						// MessageBox 题头

		/*****************************************************************************************/

		// 构造函数
        public Form_SelectSub(SelectedSubInfo selectedSubInfo, BaseCoreNet baseCoreNet, bool showPort = false)
        {
            InitializeComponent();

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			this.Font = new System.Drawing.Font(this.Font.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

			this.selectedSubInfo = selectedSubInfo;
			this.baseCoreNet = baseCoreNet;

			List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
			totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}

			string msg = string.Format("所有分控（以检测为准, {0}个）", totalSubCtrlNum);
			if (LanguageOper.available == true)
			{
				msg = string.Format(LanguageOper.ReadValue(section, "msgStr.0"), totalSubCtrlNum);
			}

			allRadioButton.Text = msg;

            if (showPort)
            {
                
            }
            else 
            {
                this.Height -= PortGroupHeight;
            }

            setPortGroupVisible(showPort);
        }

		// 构造函数
		public Form_SelectSub(SelectedSubInfo selectedSubInfo, BaseCoreNet baseCoreNet, string mode)
		{
			InitializeComponent();
			
			this.selectedSubInfo = selectedSubInfo;
			this.baseCoreNet = baseCoreNet;
			this.mode = mode;

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}

			if (mode.Equals("DownloadAddrMap"))
			{
				totalSubCtrlNumInLwf = baseCoreNet.getSubControlNumInLwf();

				string msg = string.Format("所有分控（以布线文件为准, {0}个）", totalSubCtrlNumInLwf);
				if (LanguageOper.available == true)
				{
					msg = string.Format(LanguageOper.ReadValue(section, "msgStr.1"), totalSubCtrlNumInLwf);
				}

				allRadioButton.Text = msg;
			}
			else
			{
				List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
				totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;

				string msg = string.Format("所有分控（以检测为准, {0}个）", totalSubCtrlNum);
				if (LanguageOper.available == true)
				{
					msg = string.Format(LanguageOper.ReadValue(section, "msgStr.0"), totalSubCtrlNum);
				}

				allRadioButton.Text = msg;
			}
		}

		// 设置本地化语言
		public void setLanguageText()
		{
			if (LanguageOper.available == false)
			{
				return;
			}

			LanguageOper.SetCurrentCulture();

			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 界面控件文字
			this.Text = LanguageOper.ReadValue(section, "selectSub.Text");
			allRadioButton.Text = LanguageOper.ReadValue(section, "allRadioButton.Text");
			indexRadioButton.Text = LanguageOper.ReadValue(section, "indexRadioButton.Text");
			indexMiddleLabel.Text = LanguageOper.ReadValue(section, "indexMiddleLabel.Text");
			okButton.Text = LanguageOper.ReadValue(section, "okButton.Text");
            cancelButton.Text = LanguageOper.ReadValue(section, "cancelButton.Text");
            portRadioButton.Text = LanguageOper.ReadValue(section, "portRadioButton.Text");
            portSubLabel.Text = LanguageOper.ReadValue(section, "portSubLabel.Text");
            portMiddleLabel.Text = LanguageOper.ReadValue(section, "portMiddleLabel.Text");
			if (LanguageOper.LocalLanguage != LanguageEnum.EN)
			{
				indexMiddleLabel.Location = new Point(128, 46);
			}
			else
			{
				indexMiddleLabel.Location = new Point(138, 46);
			}
		}

		// 仅允许全局模式
		public void SetOverallOnly()
		{
			indexRadioButton.Enabled = false;
            portRadioButton.Enabled = false;
		}

        // 仅允许分控模式
        public void SetSubOnly()
        {
            portRadioButton.Enabled = false;
        }

		// 按序号指定分控
		private void indexRadioButton_CheckedChanged(object sender, EventArgs e)
		{
			indexMiddleLabel.Enabled = indexRadioButton.Checked;
			indexStartTextBox.Enabled = indexRadioButton.Checked;
			indexEndTextBox.Enabled = indexRadioButton.Checked;
		}

		// 确定
		private void okButton_Click(object sender, EventArgs e)
		{
			selectedSubInfo.targetSubIndexList.Clear();

			List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
			totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;
			if (totalSubCtrlNum == 0)
			{
				string msg = "当前未检测到分控";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.2");
				}
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			if (mode.Equals("DownloadAddrMap"))
			{
				totalSubCtrlNumInLwf = baseCoreNet.getSubControlNumInLwf();
			}

            if (selectedSubInfo != null)
            {
                // 所有分控
                if (allRadioButton.Checked)
                {
                    selectedSubInfo.overall = true;
                    foreach (ControlNode node in controlNodeList)
                    {
                        if (node.type == 1)
                        {
                            selectedSubInfo.targetSubIndexList.Add(node.mySubCtrlDepth + 1);
                        }
                    }
                }
                // 按序号定位分控
                else if (indexRadioButton.Checked)
                {
                    int tmpStartIndex, tmpEndIndex;
                    if (int.TryParse(indexStartTextBox.Text.Trim(), out tmpStartIndex) && int.TryParse(indexEndTextBox.Text.Trim(), out tmpEndIndex))
                    {
                        if (tmpStartIndex < 1 || tmpStartIndex > 255)
                        {
                            string msg = "起始分控序号应在 [1,255] 区间";
                            if (LanguageOper.available == true)
                            {
                                msg = LanguageOper.ReadValue(section, "msgStr.3");
                            }
                            MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        if (tmpEndIndex < 1 || tmpEndIndex > 255)
                        {
                            string msg = "结束分控序号应在 [1,255] 区间";
                            if (LanguageOper.available == true)
                            {
                                msg = LanguageOper.ReadValue(section, "msgStr.4");
                            }
                            MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        if (tmpStartIndex > tmpEndIndex)
                        {
                            string msg = "起始分控序号大于结束分控序号, 请重新指定";
                            if (LanguageOper.available == true)
                            {
                                msg = LanguageOper.ReadValue(section, "msgStr.5");
                            }
                            MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }


                        foreach (ControlNode node in controlNodeList)
                        {
                            if (node.type == 1 && node.mySubCtrlDepth + 1 >= tmpStartIndex && node.mySubCtrlDepth + 1 <= tmpEndIndex)
                            {
                                selectedSubInfo.targetSubIndexList.Add(node.mySubCtrlDepth + 1);
                            }
                        }

                        if (selectedSubInfo.targetSubIndexList.Count == 0)
                        {
                            string msg = string.Format("未检测到序号处于 [{0}, {1}] 区间的分控", tmpStartIndex, tmpEndIndex);
                            if (LanguageOper.available == true)
                            {
                                msg = string.Format(LanguageOper.ReadValue(section, "msgStr.6"), tmpStartIndex, tmpEndIndex);
                            }
                            MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        StringBuilder excludeIndex = new StringBuilder();
                        for (int i = tmpStartIndex; i <= tmpEndIndex; i++)
                        {
                            if (!selectedSubInfo.targetSubIndexList.Contains(i))
                            {
                                excludeIndex.Append(", " + i);
                            }
                        }
                        if (!excludeIndex.ToString().Equals(""))
                        {
                            string s1 = "未检测到下列分控：";
                            string s2 = "分控{0}";
                            string s3 = "是否仍要下载其余分控？";
                            if (LanguageOper.available == true)
                            {
                                s1 = LanguageOper.ReadValue(section, "msgStr.7");
                                s2 = LanguageOper.ReadValue(section, "msgStr.8");
                                s3 = LanguageOper.ReadValue(section, "msgStr.9");
                            }

                            DialogResult dr = MessageBoxEx.Show(this, String.Format(s1 + "\n\n" + s2 + "\n\n" + s3, excludeIndex.ToString().Substring(1)), tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                            if (dr == System.Windows.Forms.DialogResult.No)
                            {
                                return;
                            }
                        }

                        selectedSubInfo.overall = false;
                    }
                    else
                    {
                        string msg = "分控编号输入错误";
                        if (LanguageOper.available == true)
                        {
                            msg = LanguageOper.ReadValue(section, "msgStr.10");
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }
                }
            }

			if (mode.Equals("reset"))
			{
				if (allRadioButton.Checked)
				{
					string msg = "确定要复位所有分控吗?";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.11");
					}

					DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

					if (dr == DialogResult.No)
					{
						this.DialogResult = DialogResult.Cancel;
					}
					else
					{
						this.DialogResult = DialogResult.OK;
					}
				}
				else
				{
					string msg = string.Format("确定要复位分控 {0} 到分控 {1} 吗？", selectedSubInfo.startIndex, selectedSubInfo.endIndex);
					if (LanguageOper.available == true)
					{
						msg = string.Format(LanguageOper.ReadValue(section, "msgStr.12"), selectedSubInfo.startIndex, selectedSubInfo.endIndex);
					}
				
					DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
					
					if (dr == DialogResult.No)
					{
						this.DialogResult = DialogResult.Cancel;
					}
					else
					{
						this.DialogResult = DialogResult.OK;
					}
				}
			}
			else
			{
                if (allRadioButton.Checked) selectMode = 0;
                else if (indexRadioButton.Checked) selectMode = 1;
                else if (portRadioButton.Checked) selectMode = 2;

                if (selectMode == 1)
                {
                    int.TryParse(indexStartTextBox.Text, out startSub);
                    int.TryParse(indexEndTextBox.Text, out endSub);
                }
                if (selectMode == 2)
                {
                    int.TryParse(portSubTextBox.Text, out startSub);
                    if (startSub < 0 || startSub > 255)
                    {
                        string msg = "分控序号应在 [1,255] 区间";
                        if (LanguageOper.available == true)
                        {
                            msg = LanguageOper.ReadValue(section, "msgStr.13");
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }
                    endSub = startSub;
                    int.TryParse(portStartTextBox.Text, out startPort);
                    if (startPort < 0 || startPort > 16)
                    {
                        string msg = "起始端口序号应在 [1,8] 区间";
                        if (LanguageOper.available == true)
                        {
                            msg = LanguageOper.ReadValue(section, "msgStr.14");
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }
                    int.TryParse(portEndTextBox.Text, out endPort);
                    if (endPort < 0 || endPort > 16)
                    {
                        string msg = "结束端口序号应在 [1,8] 区间";
                        if (LanguageOper.available == true)
                        {
                            msg = LanguageOper.ReadValue(section, "msgStr.15");
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }
                    if (startPort > endPort)
                    {
                        string msg = "起始端口序号大于结束端口序号, 请重新指定";
                        if (LanguageOper.available == true)
                        {
                            msg = LanguageOper.ReadValue(section, "msgStr.16");
                        }

                        MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }
                }
				this.DialogResult = DialogResult.OK;
			}
		}

		// 取消
		private void cancelButton_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
		}

        private void portRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            portEndTextBox.Enabled = portRadioButton.Checked;
            portStartTextBox.Enabled = portRadioButton.Checked;
            portSubTextBox.Enabled = portRadioButton.Checked;
            portSubLabel.Enabled = portRadioButton.Checked;
            portMiddleLabel.Enabled = portRadioButton.Checked;
        }

        private void setPortGroupVisible(bool visible) {
            portRadioButton.Visible = visible;
            portEndTextBox.Visible = visible;
            portStartTextBox.Visible = visible;
            portSubTextBox.Visible = visible;
            portSubLabel.Visible = visible;
            portMiddleLabel.Visible = visible;
        }
    }
}
